package com.yc.controller.xcx.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.google.gson.Gson;
import com.yc.service.xcx.user.ISessionManagerService;
import com.yc.service.xcx.user.impl.SessionManagerService;
import com.yc.util.BeanUtil;
import com.yc.util.PageData;
import com.yc.util.ReturnModel;

/**
 * 小程序过滤器
 */

public class LoginFilter implements Filter {

	private String exclude;
    private CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
	/**
	 * Default constructor.
	 */
	public LoginFilter() {
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		// TODO Auto-generated method stub
		// place your code here
		HttpServletRequest rq = (HttpServletRequest) request;
		HttpServletResponse rp = (HttpServletResponse) response;
		String rqpath = rq.getRequestURL().toString();

		ISessionManagerService sessionManagerService = (SessionManagerService) BeanUtil.getBeanFactory()
				.getBean("sessionManagerService", SessionManagerService.class);
		try {

			String path = rqpath.substring(rqpath.lastIndexOf("/") + 1, rqpath.lastIndexOf("."));

			if (!exclude.contains(path)) {
				String accessToken = "";
				String contentType = rq.getContentType();
				if (contentType.contains("multipart/form-data")) {
					MultipartHttpServletRequest multiReq = multipartResolver.resolveMultipart(rq);
					accessToken=multiReq.getParameter("AccessToken");//获取参数中的token
					request = multiReq;
				} else {
					accessToken = rq.getParameter("AccessToken");
				}

				// check login status
				PageData pd = new PageData();
				pd.put("3TDSESSION", accessToken);

				PageData result = sessionManagerService.checkloginById(pd);
				if (result == null || result.get("3TDSESSION") == null) {

					ReturnModel returnModel = new ReturnModel();
					returnModel.setResult(false);
					returnModel.setReason("会话不存在或已过时，请先登陆！");
					returnModel.setDatum(null);

					sessionManagerService.delete(pd);

					rp.reset();
					rp.setContentType("application/json");
					rp.setCharacterEncoding("utf-8");
					// 解决跨域问题
					rp.setHeader("Access-Control-Allow-Origin", "*");
					rp.getWriter().print(new Gson().toJson(returnModel));
					return;

				} else {
					// pass the request along the filter chain
					sessionManagerService.deleteAll();
					chain.doFilter(request, response);
				}

			} else {
				try {
					sessionManagerService.deleteAll();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				chain.doFilter(request, response);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
		this.exclude = fConfig.getInitParameter("exclude");
	}

}
